package com.zr.security;

import com.zr.dto.RoleDTO;
import com.zr.dto.UserDTO;
import com.zr.service.IAuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: peterChen
 * @date: 2019/11/12 10:49
 * @description: 登录认证类
 * @version: 1.0
 */
@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {
 
 
    @Autowired
    private IAuthService authService;
 
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("UserDetailsService没有接收到用户账号");
        } else {
            /**
             * 根据用户名查找用户信息
             */
            UserDTO userDto = authService.selectDtoByLoginName(username);
            //将密码摘取出来，用于框架用户验证
            String password = userDto.getPassword();
            log.info("密码：" + password);
            if(userDto == null) {
                log.error("用户'%s'不存在",username);
                throw new UsernameNotFoundException(String.format("用户'%s'不存在", username));
            }

            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            //将返回给前端用户对象中的密码设置为null防止前端可以看到密码
            //userDto.setPassword(null);
           // grantedAuthorities.add(new SimpleGrantedAuthority(JsonUtils.toString(userDto)));
            for (RoleDTO role : userDto.getRoles()) {
                log.info(username + "的角色:" + role.getName());
                //封装用户信息和角色信息到SecurityContextHolder全局缓存中

                grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            }
            /**
             * 创建一个用于认证的用户对象并返回，包括：用户名，密码，角色
             */
            return new User(userDto.getUsername(),password, grantedAuthorities);
        }
    }
}